package com.newangels.action;

import com.newangels.service.AgentManagerService;
import com.newangels.util.startAgent;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import static com.newangels.service.impl.AgentManagerServiceImpl.getAgentManagerServiceImpl;

@WebServlet("/startAllAgents")
public class StartAllAgentsServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(StartAllAgentsServlet.class.getName());
    AgentManagerService agentManagerService = getAgentManagerServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain");
        String AGENT_STATE_ = request.getParameter("AGENT_STATE_");
        String STATE_ = request.getParameter("STATE_");
        //查询 未启动状态的智能体
        List<Map<String, Object>> list = agentManagerService.selectAgents(null, null, null, null, null, AGENT_STATE_, STATE_, null, null, -1, -1);
        //启动 未启动状态的智能体
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", true);
        if (list != null) {
            String[] args = new String[3];
            try {
                for (Map<String, Object> map : list) {
                    args[0] = (String) map.get("AGENT_CODE_");
                    args[1] = (String) map.get("AGENT_URL_");
                    args[2] = (String) map.get("AGENT_ARGUMENTS_");
                    startAgent.main(args);
                }
            } catch (RuntimeException e) {
                logger.warning(args[0] + "Agent start failed\n" + e.getMessage());
                e.printStackTrace();
                jsonObject.put("success", false);
            }
        }
        response.getWriter().write(jsonObject.toString());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
